﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AB_SD_Entities;
using AB_SD_Commons.Helpers;
using System.Data.SqlClient;
using System.Data;

namespace AB_SD_DataAccess
{
    public static class CountryDAO
    {
        /// <summary>
        /// Select a country by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Country Select(int id)
        {
            Country result = new Country();

            string sql = "select * from country where id=@countryid";
            SqlParameter[] sqlparams = new SqlParameter[1];
            sqlparams[0] = new SqlParameter("@countryid", SqlDbType.Int);
            sqlparams[0].Value = id;
            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlparams);

            if (dt != null)
            {
                if (dt.Rows.Count == 1)
                {
                    result.Id = (int)dt.Rows[0]["Id"];
                    result.Name = dt.Rows[0]["Name"].ToString();                    
                    return result;
                }
                else
                    return null;
            }
            else
                return null;

            return result;
        }

        /// <summary>
        /// Select all counties in a country
        /// </summary>
        /// <param name="countryId">country id</param>
        /// <returns></returns>
        public static List<County> SelectAllCounties(int countryId)
        {
            List<County> result = new List<County>();

            string sql = "select County.Id, County.Name, County.CountryId "
            + "from (County join Country on County.CountryId = Country.Id) "
            + "where County.CountryId = @countryid";

            SqlParameter[] sqlParam = new SqlParameter[1];

            sqlParam[0] = new SqlParameter("@country", SqlDbType.Int);
            sqlParam[0].Value = countryId;

            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlParam);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        County county = new County((int)dt.Rows[i]["Id"], dt.Rows[i]["Name"].ToString(), (int)dt.Rows[i]["CountryId"]);
                        result.Add(county);
                    }
                }
            }
            return result;
        }
    }
}
